package com.mriassl.consumer.user.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.mriassl.consumer.user.domain.User;
import com.mriassl.consumer.user.service.UserService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private RestTemplate restTemplate;
	
	@Override
	@HystrixCommand(fallbackMethod="helloFallback")
	public String helloServie() {
		return restTemplate.getForObject("http://user-service/hello", String.class);
	}

	public String helloFallback(){
		System.out.println("==========helloFallback==========");
		return "error";
	}

//	@HystrixCollapser(batchMethod="findByIds", collapserProperties={
//			@HystrixProperty(name="timerDelayInMilliseconds",value="100")
//	})
	@HystrixCommand
	@Override
	public User findById(String id) {
		System.out.println("findById:"+id);
		return restTemplate.getForObject("http://user-service/user?id={1}", User.class, id);
	}

	@SuppressWarnings("unchecked")
	@HystrixCommand(fallbackMethod="findByIdsFallback")
	@Override
	public List<User> findByIds(List<String> ids) {
		System.out.println("findByIds:"+ids);
		if(ids!=null && ids.size()>0){
			return restTemplate.getForObject("http://user-service/users?ids={1}", List.class, StringUtils.join(ids, ","));
		}
		return new ArrayList<>();
	}
	
	public List<User> findByIdsFallback(List<String> ids, Throwable e) {
		System.out.println("==========findByIdsFallback:"+e.getMessage());
		return null;
	}
	
}
